﻿using System.IO;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	public static class ViewExtensions
	{
		public static string RenderPartialViewToString(this ControllerContext controllerContext)
		{
			return RenderPartialViewToString(controllerContext, null, null, null);
		}

		public static string RenderPartialViewToString(this ControllerContext controllerContext, string viewName)
		{
			return RenderPartialViewToString(controllerContext, viewName, null, null);
		}

		public static string RenderPartialViewToString(this ControllerContext controllerContext, string viewName, ViewDataDictionary viewData)
		{
			return RenderPartialViewToString(controllerContext, viewName, viewData, null);
		}

		public static string RenderPartialViewToString(this ControllerContext controllerContext, string viewName, TempDataDictionary tempData)
		{
			return RenderPartialViewToString(controllerContext, viewName, null, tempData);
		}

		public static string RenderPartialViewToString(this ControllerContext controllerContext, string viewName, ViewDataDictionary viewData, TempDataDictionary tempData)
		{
			if (string.IsNullOrEmpty(viewName))
			{
				viewName = controllerContext.RouteData.GetRequiredString("action");
			}

			var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);

			if (viewResult.View != null)
			{
				using (var writer = new StringWriter())
				{
					var viewContext = new ViewContext(controllerContext, viewResult.View, viewData ?? new ViewDataDictionary(), tempData ?? new TempDataDictionary(), writer);

					viewResult.View.Render(viewContext, writer);

					return writer.GetStringBuilder().ToString();
				}
			}

			return string.Empty;
		}
	}
}